package net.xt.testthread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 使用Semaphore进行限流
 */
public class TestSemaphoreLimit {

    // 每次只有2个线程能执行
    static Semaphore semaphore = new Semaphore(2, true);

    public static void main(String[] args) throws InterruptedException {
        // 当前任务只允许一个线程进行操作
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // 创建10个线程执行任务
        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                myService1();

//                myService2();
            });
        }
        executorService.shutdown();
    }

    /**
     * 模拟限流，一次最多只能2个线程执行业务操作
     */
    private static void myService1() {
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + "执行业务操作");
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

    /**
     * 模拟限流，最大只能2个线程执行业务操作
     */
    private static void myService2() {
        // 尝试获取锁，如果没有获取到锁，方法直接return返回，
        if (!semaphore.tryAcquire()) {
            System.out.println(Thread.currentThread().getName() + "已限流");
            return;
        }

        try {
            System.out.println(Thread.currentThread().getName() + "执行业务操作");
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

}
